import axios from "axios";
import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate, useParams } from "react-router-dom";
import { Button } from "react-vant";
import store from "../../store";
import { NavBar } from "react-vant";
import { CartO, ChatO, ShopO } from "@react-vant/icons";
import { ActionBar } from "react-vant";
const Index = () => {
  // hooks
  const dispatch = useDispatch();
  const navigate = useNavigate(-1);
  // 获取ID
  const { id } = useParams();
  // 详情数据
  const [item, setItem] = useState({});
  // 获取详情数据
  const getDetail = async () => {
    const resp = await axios.get("/api/list/detail", { params: { id } });
    console.log(resp.data.data);
    setItem(resp.data.data);
  };
  // 获取仓库数据
  const carList = useSelector((state) => state.carList);
  // 获取总数量
  const totalCount = carList.reduce((a, b) => {
    return b.count + a
  }, 0)
  useEffect(() => {
    getDetail();
  }, []);
  return (
    <div>
      <NavBar title="详情" onClickLeft={() => navigate(-1)}></NavBar>
      <img src={item.image} width={"100%"} alt="" />
      <h2>{item.title}</h2>
      <p>{item.desc}</p>
      <div
        className="btm"
        style={{ display: "flex", justifyContent: "space-between" }}
      >
        <div className="left">
          <span className="price">¥{item.price}</span>
          <span className="oldPric">
            <s>{item.oldPrice}</s>
          </span>
        </div>
        <span>销量：{item.sell}</span>
      </div>
      <ActionBar>
        <ActionBar.Icon
          icon={<ChatO />}
          text="客服"
          onClick={() => console.log("chat click")}
        />
        <ActionBar.Icon
          icon={<CartO />}
          text="购物车"
          badge={{ content: totalCount }}
          onClick={() => navigate('/car')}
        />
        <ActionBar.Icon
          icon={<ShopO />}
          text="店铺"
          onClick={() => console.log("shop click")}
        />
        <ActionBar.Button
          type="danger"
          text="加入购物车"
          onClick={() =>
            dispatch({
              type: "addToCar",
              payload: { ...item, count: 1, state: false },
            })
          }
        />
      </ActionBar>
    </div>
  );
};

export default Index;
